import * as Cesium from 'cesium'
import * as THREE from 'three';
import "/public/Cesium/Widgets/widgets.css"
import {addLight} from "@/threeJs/sceneLighting";
import {addModel} from "@/threeJs/loadModel";
import {addParkWall} from "@/threeJs/parkWall";
import {addMonitoring, displayMonitoring, monitoringViewPositioning} from "@/threeJs/monitoring";
import {createModel} from "@/threeJs/cesiumLoadModel";
import {createVehiclePositioning, carViewPositioning} from "@/threeJs/vehiclePositioning";
import {addClickCesium} from "@/threeJs/clickCesium";
import {addCompaniesTagsWalls, displayCompaniesTags} from "@/threeJs/companiesTag";
import {addWeatherSearch, displayWeatherSearch} from "@/threeJs/weatherMonitoringSearch";
import {addPublicResources, displayPublicResources} from "@/threeJs/publicResources";

export default class InitThree {
    constructor(dom) {
        this.dom = dom
        this.initCesium()
        this.currentPark = '小海子产业园'
    }

    // 初始化Cesium
    initCesium() {
        // Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90)
        window.CESIUM_BASE_URL = '/Cesium'
        // 设置cesium token
        const key1 = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMTAzZTI4YS0yNDEzLTQ2YTMtODg5Yy04ZWE2MDVhMDg1NmYiLCJpZCI6MjI3MzE1LCJpYXQiOjE3MjA1MTM5MTl9.n422GIHSN1ZG_dt4XbJQYD9P3mx0j4BZbyep-8OWDWE'
        Cesium.Ion.defaultAccessToken = key1
        // 创建Cesium Viewer
        this.cesiumViewer = new Cesium.Viewer(this.dom, {
            contextOptions: {
                requestWebgl2: true
            },
            // imageryProvider: false,
            // 关闭绿色选择边框
            selectionIndicator: false,
            // 是否显示信息窗口
            infoBox: false,
            // 是否显示查询按钮
            geocoder: false,
            // 不显示home按钮
            homeButton: false,
            // 控制查看器的显示模式
            sceneModePicker: false,
            // 是否显示图层选择
            baseLayerPicker: false,
            // 是否显示帮助按钮
            navigationHelpButton: false,
            // 是否播放动画
            animation: false,
            // 是否显示时间轴
            timeline: false,
            // 是否显示全屏按钮
            fullscreenButton: false,
            // 设置地形
            // terrainProvider:await Cesium.createWorldTerrainAsync(),
        })
        // 设置初始视角（经度, 纬度, 高度）
        this.cesiumViewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(113.80205154418947, 41.427274847023064, 4000),
            // destination: Cesium.Cartesian3.fromDegrees(113.5870134830475, 41.528330771208225, 4000),
            orientation: {
                heading: Cesium.Math.toRadians(0),    // 正北方向
                pitch: Cesium.Math.toRadians(-90),    // 向下倾斜30度
                roll: 0.0
            }
        });
        // 隐藏logo
        this.cesiumViewer.cesiumWidget.creditContainer.style.display = "none";
        // 查看帧率
        this.cesiumViewer.scene.debugShowFramesPerSecond = true
        this.loadingProgress()
        // 添加墙
        this.ParkWallArr = addParkWall(this.cesiumViewer)
        this.CompanyWallArr = addCompaniesTagsWalls(this.cesiumViewer)
        createModel(this.cesiumViewer)
        addMonitoring(this.cesiumViewer)
        createVehiclePositioning(this.cesiumViewer)
        addClickCesium(this.cesiumViewer)
        addWeatherSearch(this.cesiumViewer)
        addPublicResources(this.cesiumViewer)
        // setInterval(() => {
        //     console.log(this.cesiumViewer.camera)
        // }, 200)
    }

    initThree() {
        // 设置canvas的透明度
        this.cesiumViewer.scene.canvas.style.opcity = '0';
        // 创建地图纹理
        const mapTexture = new THREE.CanvasTexture(this.cesiumViewer.scene.canvas);
        mapTexture.minFilter = THREE.LinearFilter;
        mapTexture.magFilter = THREE.LinearFilter;
        mapTexture.wraps = THREE.ClampToEdgeWrapping
        mapTexture.wraps = THREE.ClampToEdgeWrapping
        mapTexture.colorSpace = THREE.SRGBColorSpace

        // 创建场景
        this.threeScene = new THREE.Scene();
        this.threeScene.background = mapTexture
        this.createEarth(this.threeScene)
        this.threeCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000000);
        this.threeRenderer = new THREE.WebGLRenderer({
            alpha: true,
            antialias: true,
            logarithmicDepthBuffer: true // 深度缓存
        });
        this.threeRenderer.setSize(window.innerWidth, window.innerHeight);
        this.dom.appendChild(this.threeRenderer.domElement);
        this.threeRenderer.domElement.style.position = 'absolute';
        this.threeRenderer.domElement.style.top = '0';
        this.threeRenderer.domElement.style.left = '0';
        this.threeRenderer.domElement.style.pointerEvents = 'none';
        // 重置模型页面宽高比
        const resetCameraAspect = () => {
            // 重置相机宽高比
            this.threeCamera.aspect = window.innerWidth / window.innerHeight;
            // 更新相机投影矩阵
            this.threeCamera.updateProjectionMatrix();
            // 重置渲染器宽高比
            this.threeRenderer.setSize(window.innerWidth, window.innerHeight);
            // 重置渲染器的像素比例
            this.threeRenderer.setPixelRatio(window.devicePixelRatio);
        }
        // 监听窗口变化，响应式页面
        // window.addEventListener('resize', resetCameraAspect);
        //添加光源
        addLight(this.threeScene)
        //添加模型
        addModel(this.threeScene)
        // addMonitoring(this.threeScene)
        const render = () => {
            mapTexture.needsUpdate = true
            requestAnimationFrame(render);
            this.syncThreeCamera()
            this.threeRenderer.render(this.threeScene, this.threeCamera);
            // console.log(this.cesiumViewer.camera)
            // console.log(this.cesiumViewer.entities)
        }
        render();
    }

    flyToCompanies(name) {
        if (name) {
            this.CompanyWallArr.then((res) => {
                res.forEach(item => {
                    if (item.name === name) {
                        item.show()
                        displayCompaniesTags(this.cesiumViewer, true, name)
                    } else {
                        item.hide()
                    }
                })
            })
        } else {
            displayCompaniesTags(this.cesiumViewer, false)
            this.CompanyWallArr.then((res) => {
                res.forEach(item => {
                    item.hide()
                })
            })
        }
    }

    flyToMonitoring(name) {
        if (name) {
            monitoringViewPositioning(this.cesiumViewer, name)
        }
    }

    flyToCompaniesClass(arr) {
        if (arr) {
            displayCompaniesTags(this.cesiumViewer, true, arr)
            this.defaultView(this.currentPark)
            this.CompanyWallArr.then((res) => {
                res.forEach(item => {
                    item.hide()
                })
            })
            this.CompanyWallArr.then((res) => {
                res.forEach(item => {
                    arr.forEach(param => {
                        if (item.name === param.enterpriseName) {
                            item.show()
                        }
                    })
                })
            })
        }
    }

    monitoringShow(flag) {
        displayMonitoring(this.currentPark, this.cesiumViewer, flag)
    }

    weatherSearchShow(flag, info) {
        displayWeatherSearch(this.cesiumViewer, flag, info)
    }

    publicResourcesShow(flag, info) {
        displayPublicResources(this.cesiumViewer, flag, info)
    }

    carViewPos(objectId) {
        carViewPositioning(this.cesiumViewer, objectId)
    }

    defaultView(name: string) {
        let arr = []
        if (name === '三大顷产业园') {
            arr = [113.53233933448793, 41.42128950761943, 4000]
            this.currentPark = '三大顷产业园'
            // this.cesiumViewer.entities.getById('三大顷西模型').show = true
            // this.cesiumViewer.entities.getById('小海子模型').show = false
        } else if (name === '小海子产业园') {
            this.currentPark = '小海子产业园'
            arr = [113.80205154418947, 41.427274847023064, 4000]
            // this.cesiumViewer.entities.getById('小海子模型').show = true
            // this.cesiumViewer.entities.getById('三大顷西模型').show = false
        } else if (name === '七台镇西产业园') {
            arr = [113.50908994674684, 41.53899626433991, 4000]
            this.currentPark = '七台镇西产业园'
            // this.cesiumViewer.entities.getById('小海子模型').show = true
            // this.cesiumViewer.entities.getById('三大顷西模型').show = false
        } else if (name === '七台镇东产业园') {
            this.currentPark = '七台镇东产业园'
            arr = [113.5870134830475, 41.528330771208225, 4000]
            // this.cesiumViewer.entities.getById('小海子模型').show = true
            // this.cesiumViewer.entities.getById('三大顷西模型').show = false
        }
        // // 指定相机位置
        // destination: {
        //     x: -1935415.6753515878,
        //         y: 4385336.742480193,
        //         z: 4201404.580330647
        // },
        this.cesiumViewer.camera.flyTo({
            // 指定相机位置
            destination: Cesium.Cartesian3.fromDegrees(
                arr[0], arr[1], arr[2]
            ),
            orientation: {
                // 指定相机的朝向,偏航角
                heading: Cesium.Math.toRadians(0),
                // 指定相机的俯仰角,0度是竖直向上,-90度是向下
                pitch: Cesium.Math.toRadians(-90),
                // 指定相机的滚转角,翻滚角
                roll: 0,
            },
            duration: 2,
            start: () => {
                // console.log("飞行动画开始！");
            },
            complete: () => {
                // console.log("飞行动画执行完毕！");
            },
            cancel: () => {
                // console.log("飞行动画被取消！");
            }
        });
    }

    createEarth() {
        const earthGeometry = new THREE.SphereGeometry(6374000, 64, 64);
        const earthMaterial = new THREE.MeshPhongMaterial({color: 0x00ff00, colorWrite: false});
        const earthMesh = new THREE.Mesh(earthGeometry, earthMaterial)
        this.threeScene.add(earthMesh)
    }

    loadingProgress() {
        // 监听地图切片加载进度
        const globe = this.cesiumViewer.scene.globe;
        globe.tileLoadProgressEvent.addEventListener(pendingRequests => {
            this.loadProgress = Math.max(0, 100 - pendingRequests);
        });
    }

    syncThreeCamera() {
        // 将three的相机视野角度与cesium的相机视野角度同步
        this.threeCamera.fov = Cesium.Math.toDegrees(this.cesiumViewer.camera.frustum.fovy);
        // 更新相机投影矩阵
        this.threeCamera.updateProjectionMatrix();
        // 更新相机位置和旋转矩阵
        this.threeCamera.matrixAutoUpdate = false;// 禁用自动更新相机矩阵
        let cvm = this.cesiumViewer.camera.viewMatrix;
        let civm = this.cesiumViewer.camera.inverseViewMatrix;
        // 设置相机的位置
        this.threeCamera.position.set(civm[12], civm[13], civm[14]);
        this.threeCamera.lookAt(0, 0, 0);
        // 设置相机矩阵
        this.threeCamera.matrixWorld.set(
            civm[0], civm[4], civm[8], civm[12],
            civm[1], civm[5], civm[9], civm[13],
            civm[2], civm[6], civm[10], civm[14],
            civm[3], civm[7], civm[11], civm[15]
        );
        // 相机逆矩阵
        this.threeCamera.matrixWorldInverse.set(
            cvm[0], cvm[4], cvm[8], cvm[12],
            cvm[1], cvm[5], cvm[9], cvm[13],
            cvm[2], cvm[6], cvm[10], cvm[14],
            cvm[3], cvm[7], cvm[11], cvm[15]
        );
    }
}
